<?php

class DonationController extends App_Controller_Action
{
	private $paypalIPN;
		
    public function init()
    {
        // load election config values
        $filepath = APPLICATION_PATH . '/configs/election.ini';       
        $config = new Zend_Config_Ini($filepath, null,                              
		    		array(
		    			'skipExtends'        => true,                                    
		    			'allowModifications' => true
		    		)
		);    
    	// Initialize paypal 
    	$this->paypalIPN = new App_Service_PayPal( ROOT_PATH.'/tmp/ipn.log', $config->paypal->test );
    }

    public function indexAction()
    {
        
    }
    
    public function requestAction()
    {
    	$request = $this->getRequest();
        $this->_redirector = $this->_helper->getHelper('Redirector');
    	
        $form = new Form_RequestDonation();
        $this->view->form = $form;
        
	    if ($this->getRequest()->isPost()) {
	
            $formData = $this->getRequest()->getPost();

            if ($form->isValid($formData)) {

            	// update user profile		        
				$user = Doctrine_Core::getTable("Users")->find($this->getUserId());
				$user->gender = $formData['gender'];
				$user->age = $formData['age'];
				$user->id_ethnicity = $formData['ethnicity'];
				$user->updateWithNoPassword();

            	// save project data		        
            	$project = new Projects();
				$project->fromArray($form->getValues(true));
				$project->title = $formData['title'];
		        $project->id_user = $this->getUserId();
				$project->allow_contest = 1;
				$project->contest = 1;
		        $project->save();
		    	$project->refresh();

		    	// save project pictures		        
				$pp = new ProjectPictures();
				$pp->filename = $formData['filename'];
				$pp->id_project = $project->id_project;
				$pp->save();
				$pp->refresh();

		        // open log file
				$writer = new Zend_Log_Writer_Stream ( ROOT_PATH.'/tmp/election.log' );
				$logger = new Zend_Log ( $writer );
				$funds = $donation->amount; $username = $user->username;
				$id = $project->id_project; $title = $project->title;
				$logger->info ( "request donation: user:$username project:$id($title) funds:$funds" );
				
				// show the vote screen
	            $this->_redirector->gotoSimple("vote", "election");
			} 
            else{
                $form->populate($formData);
            }
        }
    }
    
    public function donateAction()
    {
        $request = $this->getRequest();
        $this->_redirector = $this->_helper->getHelper('Redirector');
        
        $form = new Form_Donate();
        $this->view->form = $form;
        
	    if ($request->isPost()) {
	
            $formData = $request->getPost();

            if ($form->isValid($formData)) {				

	            // save donation data		        
				$donation = new Donations();
				$donation->fromArray($form->getValues(true));
		        $donation->id_user = $this->getUserId();
				$donation->donation_date = new Doctrine_Expression("NOW()");
				$donation->valid = 0;
				$donation->save();
		    	$donation->refresh();
            					
            	// do payment with PayPal
				$this->_redirector->gotoSimple("payment", "donation", null, array('id' => $donation->id_donation ));
            } 
            else{
                $form->populate($formData);
            }
        }        
    }
    
    public function notificationAction() {
        
    }
    
    public function paymentAction() {
    	$id = $this->_getParam('id', 0);    	
    	// disabled the layout
		// $this->_helper->layout->disableLayout();
        // load election config values
        $filepath = APPLICATION_PATH . '/configs/election.ini';       
        $config = new Zend_Config_Ini($filepath, null,                              
		    		array(
		    			'skipExtends'        => true,                                    
		    			'allowModifications' => true
		    		)
		);    
		// donation info
		$this->paypalIPN->addSubmitField('return', ROOT_URL . $this->_helper->url('notification','donation') );
		$this->paypalIPN->addSubmitField('business', $config->paypal->email);
		$this->paypalIPN->addSubmitField('item_name', 'Social Giving Donation');
		$this->paypalIPN->addSubmitField('item_number', $id);
		// save donation
		$donation = Doctrine_Core::getTable('Donations')->find($id);
		$this->paypalIPN->addSubmitField('amount', $donation->amount);
		$this->paypalIPN->addSubmitField('address1', $donation->address);
		$this->paypalIPN->addSubmitField('city', $donation->city);
		$this->paypalIPN->addSubmitField('state', $donation->id_state);
		$this->paypalIPN->addSubmitField('country', $donation->id_country);
		$this->paypalIPN->addSubmitField('zip', $donation->zip);
		// user info
		$user = Doctrine_Core::getTable('Users')->find($this->getUserId());
		$this->paypalIPN->addSubmitField('first_name', $user->first_name);
		$this->paypalIPN->addSubmitField('last_name', $user->last_name);
		$this->paypalIPN->addSubmitField('night_phone_a', $user->phone_number);
		$this->paypalIPN->addSubmitField('email', $user->email);
		// paypal object to the view
		$this->view->url = $this->paypalIPN->getURL_PayPal();
		$this->view->fields = $this->paypalIPN->getSubmitFields();
    }
    
    public function ipnAction() {
		
		if ($this->paypalIPN->validateIPN()) {
			
			// get data from IPN
			$data = $this->paypalIPN->getIPNData();
			
            // check and save transaction id
            $transaction = Doctrine_Core::getTable('Transactions')->findOneById_transac($data['txn_id']);
            if ($transaction) {
            	// this transaction was already made
            	return;
            }
            // save new transaction
            $transaction = new Transactions();		        
			$transaction->id_transac = $data['txn_id'];
			$transaction->email = $data['payer_email'];
			$transaction->save();
	    	$transaction->refresh();

	    	// save donation data
            $donation = Doctrine_Core::getTable('Donations')->find($data['item_number']);		        
			$donation->valid = 1;
			$donation->save();
	    	$donation->refresh();
	    	
            // update user profile		        
			$user = Doctrine_Core::getTable("Users")->find($donation->id_user);
			$user->allow_vote = 1;
			$user->updateWithNoPassword();
	    	
            // update balance		        
			$balance = new FundsBalance();
	        $balance->amount = $donation->amount;
			$balance->type_trans = 1;
	        $balance->id_user = $donation->id_user;
			$balance->date_trans = $donation->donation_date;							
	    	$balance->save();
	    	$balance->refresh();

	        // open log file
			$writer = new Zend_Log_Writer_Stream ( ROOT_PATH.'/tmp/election.log' );
			$logger = new Zend_Log ( $writer );
			$funds = $donation->amount; $username = $user->username;
			$logger->info ( "user donate: user:$username funds:$funds" );
			
            // donation success
        	$this->view->error = false;
        	$this->view->data = $data;
		}
        else {
            // donation error
        	$this->view->error = true;
        }
		
	}
}

